package com.sailing.lianxi.algorithm;

import com.sailing.lianxi.common.SortEnum;

import java.util.Arrays;

/**
 * 冒泡排序
 * @author Administrator
 *
 */
public class BubbleSort {

	public static void t1(int array[],String type) {
		int tmp = 0;
		for(int i=0;i<array.length;i++) {
			for(int j=0;j<array.length-i-1;j++) {
				if(SortEnum.ASC.getKey().equals(type)) {
					if(array[j]>array[j+1]) {
						dataExchange(array,j);
					}
				}else if(SortEnum.DESC.getKey().equals(type)) {
					if(array[j]<array[j+1]) {
						dataExchange(array,j);
					}
				}
			}
		}
		
		System.out.println(SortEnum.getValueByKey(type)+"排序结果："+Arrays.toString(array));
	}
	
	/**
	 * 优化的排序算法
	 * @param array
	 * @param type
	 */
	public static void t2(int array[],String type) {
		int tmp = 0;
		for(int i=0;i<array.length;i++) {
			for(int j=0;j<array.length-i-1;j++) {
				if(SortEnum.ASC.getKey().equals(type)) {
					if(array[j]>array[j+1]) {
						dataExchange(array,j);
					}
				}else if(SortEnum.DESC.getKey().equals(type)) {
					if(array[j]<array[j+1]) {
						dataExchange(array,j);
					}
				}
			}
		}
		
		System.out.println(SortEnum.getValueByKey(type)+"排序结果："+Arrays.toString(array));
	}
	
	
	private static void  dataExchange(int array[],int index) {
		int tmp = array[index];
		array[index] = array[index+1];
		array[index+1] = tmp;
	}
	
	public static void main(String[] args) {
		 int[] array = new int[]{5,8,6,3,9,2,1,7};
		t1(array,SortEnum.ASC.getKey());
		t1(array,SortEnum.DESC.getKey());
		System.out.println("2222");
	}
}
